<?php
require_once 'bank-class.php';

class PaymentCommBank extends Bank {
	protected $version	= '1';			// Version of CommWeb Virtual Payment Client API
	protected $command	= 'pay';			// Type of transaction
	
	function __construct($data){
		parent::__construct($data);
		
	}

	function Submit(){
		return parent::Submit();
	}
	
	
	/*
	 * Submit payment request and return result
	*/
	function SubmitPayment(){
	
		$this->CreatePOSTRequest();
		try{	
			// Send XML request using CURL
			$ch = curl_init();
			curl_setopt_array($ch, array(
			CURLOPT_URL => $this->url_to_use,
			CURLOPT_HEADER => false,
			CURLOPT_POST => true,
			CURLOPT_POSTFIELDS => trim($this->post_request),
			CURLOPT_RETURNTRANSFER => true,
			));
		
			// Execute query and get response
			$this->post_response = curl_exec($ch);	
			if(curl_error($ch)) $this->errorMsg .= ' -> BANK CONNECTION ERROR -> ['. curl_errno($ch) . '] ' . curl_error($ch);
			$this->ProcessResponse();
			curl_close($ch);
		}catch (Exception $e){
			$this->errorMsg .= ' -> BANK CONNECTION ERROR -> ' . $e;
		}
	}
	

	
	/*
	 * Process the response
	*/
	function ProcessResponse(){
		$responseArr = array(); 
		
		// Convert response to array
		$setArr = explode('&', $this->post_response);
		foreach($setArr as $s){
			$valArr = explode('=', $s);
			$responseArr["{$valArr[0]}"] = $valArr[1]; 
		}
		$this->response['payment_response']	= $this->post_response;
		$this->response['cardscheme']       = 'Credit Card';
		$this->response['receipt_no']       = $responseArr["vpc_ReceiptNo"];
		$this->response['summary_code']			= $responseArr["vpc_AcqResponseCode"];
		$this->response['code']							= $responseArr["vpc_TxnResponseCode"];
		$this->response['msg']							= $responseArr["vpc_Message"];
	}
	
	
	/*
	 * Check payment status and set status variable and error messages accordingly
	*/
	function CheckPaymentStatus(){
		if($this->response['code'] == "0"){
			// Payment successful
			$this->response['payment_status'] = 'A';
			$this->payment_success = true;
		}else{
			// Payment failed
			$this->response['payment_status'] = 'F';
			$this->payment_success = false;
			$this->errorMsg .= ' -> PAYMENT FAILED: ['.$this->response['code'].'] '.$this->getResponseDescription($this->response['code']); 
// 			if($_SERVER['REMOTE_ADDR'] == '150.101.230.130'){ $this->errorMsg .= print_r($this->response, true); }
		}
	
	}
	
	function CreatePOSTRequest(){
		$fields = array(
				'vpc_Version'=>urlencode($this->version),
				'vpc_Command'=>urlencode($this->command),
				'vpc_MerchTxnRef'=>urlencode($this->messageID),
				'vpc_AccessCode'=>urlencode($this->merchant_password),
				'vpc_Merchant'=>urlencode($this->merchant_id),
				'vpc_OrderInfo'=>urlencode($this->payment_transactionno),
				'vpc_Amount'=>urlencode($this->FormatToCents($this->amount)),
				'vpc_CardNum'=>urlencode($this->cc_number),
				'vpc_CardExp'=>urlencode($this->cc_expiry_year . $this->cc_expiry_month),
				'vpc_CardSecurityCode'=>urlencode($this->cc_cvc)
		);
			
		//url-ify the data for the POST
		foreach($fields as $key=>$value) {
			$fields_string .= $key.'='.$value.'&';
		}
		rtrim($fields_string,'&');
			
		$this->post_request = $fields_string;
		return $this->post_request;
	}


	
	/********************************************************************************
	 * ******************************************************************************
	*
	* THE FOLLOWING CODE WAS COPIED FROM RSGK OLD SITE
	*
	* ******************************************************************************
	* ******************************************************************************
	*/
	
	function getResponseDescription($responseCode) {
		switch ($responseCode) {
			//case "7" : $result = "Payment Server System Error"; break;
			case "0" : $result = "Transaction Successful"; break;
			case "?" : $result = "Transaction status is unknown"; break;
			case "1" : $result = "Unknown Error"; break;
			case "2" : $result = "Bank Declined Transaction"; break;
			case "3" : $result = "No Reply from Bank"; break;
			case "4" : $result = "Expired Card"; break;
			case "5" : $result = "Insufficient funds"; break;
			case "6" : $result = "Error Communicating with Bank"; break;
			case "7" : $result = "Invalid Card Number"; break;
			case "8" : $result = "Transaction Type Not Supported"; break;
			case "9" : $result = "Bank declined transaction (Do not contact Bank)"; break;
			case "A" : $result = "Transaction Aborted"; break;
			case "C" : $result = "Transaction Cancelled"; break;
			case "D" : $result = "Deferred transaction has been received and is awaiting processing"; break;
			case "F" : $result = "3D Secure Authentication failed"; break;
			case "I" : $result = "Card Security Code verification failed"; break;
			case "L" : $result = "Shopping Transaction Locked (Please try the transaction again later)"; break;
			case "N" : $result = "Cardholder is not enrolled in Authentication scheme"; break;
			case "P" : $result = "Transaction has been received by the Payment Adaptor and is being processed"; break;
			case "R" : $result = "Transaction was not processed - Reached limit of retry attempts allowed"; break;
			case "S" : $result = "Duplicate SessionID (OrderInfo)"; break;
			case "T" : $result = "Address Verification Failed"; break;
			case "U" : $result = "Card Security Code Failed"; break;
			case "V" : $result = "Address Verification and Card Security Code Failed"; break;
			default  : $result = "Unable to be determined - ".$responseCode;
		}
		return $result;
	}
	
	//  ----------------------------------------------------------------------------
	
	// This function uses the QSI AVS Result Code retrieved from the Digital
	// Receipt and returns an appropriate description for this code.
	
	// @param vAVSResultCode String containing the QSI AVS Result Code
	// @return description String containing the appropriate description
	
	function displayAVSResponse($avsResultCode) {
			
		if ($avsResultCode != "") {
			switch ($avsResultCode) {
				Case "Unsupported" : $result = "AVS not supported or there was no AVS data provided"; break;
				Case "X"  : $result = "Exact match - address and 9 digit ZIP/postal code"; break;
				Case "Y"  : $result = "Exact match - address and 5 digit ZIP/postal code"; break;
				Case "S"  : $result = "Service not supported or address not verified (international transaction)"; break;
				Case "G"  : $result = "Issuer does not participate in AVS (international transaction)"; break;
				Case "A"  : $result = "Address match only"; break;
				Case "W"  : $result = "9 digit ZIP/postal code matched, Address not Matched"; break;
				Case "Z"  : $result = "5 digit ZIP/postal code matched, Address not Matched"; break;
				Case "R"  : $result = "Issuer system is unavailable"; break;
				Case "U"  : $result = "Address unavailable or not verified"; break;
				Case "E"  : $result = "Address and ZIP/postal code not provided"; break;
				Case "N"  : $result = "Address and ZIP/postal code not matched"; break;
				Case "0"  : $result = "AVS not requested"; break;
				default   : $result = "Unable to be determined - ".$avsResultCode;
			}
		} else {
			$result = "null response";
		}
		return $result;
	}
	
	//  ----------------------------------------------------------------------------
	
	// This function uses the QSI CSC Result Code retrieved from the Digital
	// Receipt and returns an appropriate description for this code.
	
	// @param vCSCResultCode String containing the QSI CSC Result Code
	// @return description String containing the appropriate description
	
	function displayCSCResponse($cscResultCode) {
			
		if ($cscResultCode != "") {
			switch ($cscResultCode) {
				Case "Unsupported" : $result = "CSC not supported or there was no CSC data provided"; break;
				Case "M"  : $result = "Exact code match"; break;
				Case "S"  : $result = "Merchant has indicated that CSC is not present on the card (MOTO situation)"; break;
				Case "P"  : $result = "Code not processed"; break ;
				Case "U"  : $result = "Card issuer is not registered and/or certified"; break;
				Case "N"  : $result = "Code invalid or not matched"; break;
				default   : $result = "Unable to be determined - ".$cscResultCode; break;
			}
		} else {
			$result = "null response";
		}
		return $result;
	}
	
	
	function getResponseCodeDescription($code){
		switch ($code) {
			case '00':$description = "Approved";break;
			case '01':$description = "Refer to Card Issuer";break;
			case '02':$description = "Refer to Card Issuer";break;
			case '03':$description = "Invalid Merchant";break;
			case '04':$description = "Pick Up Card";break;
			case '05':$description = "Do Not Honor";break;
			case '07':$description = "Pick Up Card";break;
			case '12':$description = "Invalid Transaction";break;
			case '14':$description = "Invalid Card Number";break;
			case '15':$description = "No Such Issuer";break;
			case '33':$description = "Expired Card";break;
			case '34':$description = "Suspected Fraud";break;
			case '36':$description = "Restricted Card";break;
			case '39':$description = "No Credit Account";break;
			case '41':$description = "Card Reported Lost";break;
			case '43':$description = "Stolen Card";break;
			case '51':$description = "Insufficient Funds";break;
			case '54':$description = "Expired Card";break;
			case '57':$description = "Transaction Not Permitted";break;
			case '59':$description = "Suspected Fraud";break;
			case '62':$description = "Restricted Card";break;
			case '65':$description = "Exceeds withdrawal frequency limit";break;
			case '81':$description = "Desclined, CSC not accepted";break;
			case '91':$description = "Cannot Contact Issuer";break;
			default  :$description = "Unable to be determined - ".$code; break;
		}
		return $description;
			
	}
	
	//  -----------------------------------------------------------------------------
	
	// This method uses the verRes status code retrieved from the Digital
	// Receipt and returns an appropriate description for the QSI Response Code
	
	// @param statusResponse String containing the 3DS Authentication Status Code
	// @return String containing the appropriate description
	
	function getStatusDescription($statusResponse) {
		if ($statusResponse == "" || $statusResponse == "No Value Returned") {
			$result = "3DS not supported or there was no 3DS data provided";
		} else {
			switch ($statusResponse) {
				Case "Y"  : $result = "The cardholder was successfully authenticated."; break;
				Case "E"  : $result = "The cardholder is not enrolled."; break;
				Case "N"  : $result = "The cardholder was not verified."; break;
				Case "U"  : $result = "The cardholder's Issuer was unable to authenticate due to some system error at the Issuer."; break;
				Case "F"  : $result = "There was an error in the format of the request from the merchant."; break;
				Case "A"  : $result = "Authentication of your Merchant ID and Password to the ACS Directory Failed."; break;
				Case "D"  : $result = "Error communicating with the Directory Server."; break;
				Case "C"  : $result = "The card type is not supported for authentication."; break;
				Case "S"  : $result = "The signature on the response received from the Issuer could not be validated."; break;
				Case "P"  : $result = "Error parsing input from Issuer."; break;
				Case "I"  : $result = "Internal Payment Server system error."; break;
				default   : $result = "Unable to be determined - ".$statusResponse; break;
			}
		}
		return $result;
	}
	
	
}